package org.custom.ibatis.session;

import org.custom.ibatis.datasource.JNDIDataSource;
import org.custom.ibatis.datasource.PooledDataSource;
import org.custom.ibatis.datasource.UnPooledDataSource;
import org.custom.ibatis.io.Resources;
import org.custom.ibatis.transaction.JDBCTransactionManager;
import org.custom.ibatis.transaction.ManagedTransactionManager;
import org.custom.ibatis.transaction.TransactionManager;
import org.dom4j.Document;
import org.dom4j.Element;
import org.dom4j.Node;
import org.dom4j.io.SAXReader;

import javax.sql.DataSource;
import java.io.InputStream;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author DJJ_F
 * @version 1.0
 * @date 2025/02/25
 * @description 这里还应该写一个常量类，更规范
 */
public class SqlSessionFactoryBuilder {
    public SqlSessionFactoryBuilder() {
    }

    /**
     * 这里需要解析xml文件来获取 SqlSessionFactory对象
     * 需要提供：数据源
     * 事务管理器
     * mappers的map集合
     *
     * @param inputStream
     * @return
     */
    public SqlSessionFactory build(InputStream inputStream) {
        // 事务管理器
        TransactionManager txManager = null;
        // sql语句的map集合
        Map<String, MapperStatement> mappers = null;
        // 解析xml文件
        SAXReader saxReader = new SAXReader();
        try {
            Document document = saxReader.read(inputStream);
            Element environments = (Element) document.selectSingleNode("/configuration/environments");
            String defaultId = environments.attributeValue("default");
            Element env = (Element) document.selectSingleNode("/configuration/environments/environment[@id='" + defaultId + "']");

            Element dataSourceEle = env.element("dataSource");
            DataSource dataSource = getDataSource(dataSourceEle);

            Element transactionEle = env.element("transactionManager");
            txManager = getTransactionManager(transactionEle, dataSource);

            // 这是所以mapper标签的list集合对象
            List<Node> mapperList = document.selectNodes("//mapper");
            mappers = getMappers(mapperList);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        return new SqlSessionFactory(txManager, mappers);
    }

    /**
     * @param mapperList 传入的是mapper标签的list集合对象
     * @return
     */
    private Map<String, MapperStatement> getMappers(List<Node> mapperList) {
        Map<String, MapperStatement> map = new HashMap<>();
        mapperList.forEach(node -> {
            // 这是单个mapper 标签
            Element element = (Element) node;
            // 获取单个xml文件的路径
            String resourcePath = element.attributeValue("resource");
            SAXReader saxReader = new SAXReader();
            try {
                Document document = saxReader.read(Resources.getResourceAsStream(resourcePath));
                // 这是mapper根标签
                Element mappers = document.getRootElement();
                String namespace = mappers.attributeValue("namespace");
                // 遍历下面的sql语句标签
                mappers.elements().forEach(statement -> {
                    String id = statement.attributeValue("id");
                    String resultType = statement.attributeValue("resultType");
                    String sql = statement.getTextTrim();
                    String sqlId = namespace + "." + id;
                    MapperStatement mapperStatement = new MapperStatement(sql, resultType);
                    map.put(sqlId, mapperStatement);
                });
            } catch (Exception e) {
                throw new RuntimeException(e);
            }
        });
        return map;
    }

    private DataSource getDataSource(Element dataSourceEle) {
        Map<String, String> map = new HashMap<>();
        List<Element> properties = dataSourceEle.elements("property");
        properties.forEach(property -> {
            String name = property.attributeValue("name");
            String value = property.attributeValue("value");
            map.put(name, value);
        });
        String type = dataSourceEle.attributeValue("type").trim().toUpperCase();
        DataSource dataSource = null;
        if ("UNPOOLED".equals(type)) {
            dataSource = new UnPooledDataSource(map.get("driver"), map.get("url"), map.get("username"), map.get("password"));
        } else if ("POLLED".equals(type)) {
            dataSource = new PooledDataSource();
        } else if ("JNDI".equals(type)) {
            dataSource = new JNDIDataSource();
        }
        return dataSource;
    }

    private TransactionManager getTransactionManager(Element transactionEle, DataSource dataSource) {
        String type = transactionEle.attributeValue("type").trim().toUpperCase();
        TransactionManager transactionManager = null;
        if ("JDBC".equals(type)) {
            transactionManager = new JDBCTransactionManager(dataSource, false);
        } else if ("MANAGED".equals(type)) {
            transactionManager = new ManagedTransactionManager();
        }
        return transactionManager;
    }
}
